//
//  ConfigurationManager.m
//  mUBB
//
//  Created by Cosmin Stirbu on 2/23/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "ConfigurationManager.h"

@implementation ConfigurationManager

// Singleton
+ (ConfigurationManager *)instance
{
    static ConfigurationManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[ConfigurationManager alloc] init];
        // Do any other initialisation stuff here
    });
    return instance;
}

- (id)init {
    self = [super init];
    NSString *rootPath = [[NSBundle mainBundle] bundlePath];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // Application Config
    NSString *appConfigBundlePath = [rootPath stringByAppendingPathComponent:@"ApplicationConfig.plist"];

    _appConfigPath = [documentsDirectory stringByAppendingPathComponent:@"ApplicationConfig.plist"];

    
    if (![fileManager fileExistsAtPath: _appConfigPath])
    {
        _appConfigDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:appConfigBundlePath];
        [_appConfigDictionary writeToFile:_appConfigPath atomically:NO];
    } else {
        _appConfigDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:_appConfigPath];
    }
    
    // UI Config
    _uiConfigPath = [rootPath stringByAppendingPathComponent:@"UIConfig.plist"];
    _uiConfigDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:_uiConfigPath];
    
    return self;
}
- (id)applicationConfigValueForKey:(NSString *)key {
    return [_appConfigDictionary objectForKey:key];
}

- (void)setApplicationConfigValue:(id)value forKey:(NSString *)key {
    if (value != nil) {
        [_appConfigDictionary setObject:value forKey:key];
    }
}

- (id)UIConfigValueForKey:(NSString *)key {
    return [_uiConfigDictionary objectForKey:key];
}

- (void)saveApplicationConfig {
    [_appConfigDictionary writeToFile:_appConfigPath atomically:NO];
}

@end
